using System;
using System.Collections;
using System.Security.Principal;
using Castle.ActiveRecord;
using Castle.Components.Validator;
using NHibernate.Expression;

namespace DecisionesInteligentes.iEvalua.Models
{
	/// <summary>
	/// An instance of this class represents a User.
	/// </summary>
	[ActiveRecord("Users")]
	public class User : ActiveRecordValidationBase<User>, IPrincipal, IEntity	{
		
		#region Persistent properties
		[PrimaryKey]
		public int Id {
			get;
			set;
		}
		[Property]
		[ValidateNonEmpty("Name cannot be empty")]
		public string Name {
			get;
			set;
		}
		[Property]
		[ValidateNonEmpty("Username cannot be empty")]
		public string Username {
			get;
			set;
		}
		[Property]
		[ValidateEmail("Email is not valid")]
		[ValidateNonEmpty("Email cannot be empty")]
		public string Email {
			get;
			set;
		}
		[Property]
		[ValidateNonEmpty("Password cannot be empty")]
		[ValidateSameAs("ConfirmPassword")]
		public string Password {
			get;
			set;
		}
		[ValidateNonEmpty("ConfirmPassword cannot be empty")]
		public string ConfirmPassword{
			get;
			set;
		}
		[Property]
		public DateTime LastLoginDate {
			get;
			set;
		}
		[Property]
		public DateTime LastLockoutDate {
			get;
			set;
		}
		[Property]
		public DateTime CreationDate {
			get;
			set;
		}
		[Property]
		public bool IsApproved {
			get;
			set;
		}
		[Property]
		public bool IsLocked {
			get;
			set;
		}
		#endregion
		
		[BelongsTo("ApplicationId")]
		[ValidateNonEmpty("Application cannot be empty")]
		public Application Application
		{
			get;
			set;
		}
		
		public IIdentity Identity
		{
			get
			{
				return new GenericIdentity(Name, "DecisionesInteligentes.iEvalua.Authentication");
			}
		}
		
		public bool IsInRole(string role)
		{
			return false;
		}
		
		public int GetId()
		{
			return Id;
		}
		
		public static User FindAllByUsernameAndApplication(string username, int applicationId)
		{
			User[] users = User.FindAll(new ICriterion[]
				{ 
					new EqExpression("Username", username), new EqExpression("ApplicationId", applicationId) 
				}
			);
			
			if(users.Length == 0)
				return null;
			else
				return users[0];
		}
	}

}
